package com.naiterui.ehp.bs.ds.common.interceptor;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;

import com.naiterui.ehp.bp.security.utils.SecurityUtils;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bp.support.utils.JsonMapper;
import com.naiterui.ehp.bs.ds.common.exception.BusinessExceptionCode;
import com.naiterui.ehp.bs.ds.common.utils.JwtUser;

/**
 * 密码过期后需要重新修改密码
 *
 * @author 王泽浩
 * @date 2019-06-22 11:23
 * @since 1.0.0
 */
public class PasswordExpireInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        JwtUser user;
        try {
            user = SecurityUtils.getCurrentUser();
        } catch (Exception e) {
            return true;
        }
        //判断是否90天，如果90则需要重新修改密码
        Date lastPasswordResetDate = user.getLastPasswordResetDate();
        LocalDate endDate = lastPasswordResetDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        long until = endDate.until(LocalDate.now(), ChronoUnit.DAYS);
        if (until > 90) {
            response.setContentType("application/json;charset=utf-8");
            ResponseVO<String> responseVO = PublicService.returnResponseVO(BusinessExceptionCode.PASSWORD_EXPIRE, "系统检测您当前密码已使用超过90天，为保证您的账号安全，请立即修改密码");
            response.getWriter().print(JsonMapper.toJson(responseVO));
            return false;
        }
        return true;
    }

}
